package com.bulletelc.apollopre.module.main.center;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.constants.IntentCode;
import com.bulletelc.apollopre.constants.SPKey;
import com.bulletelc.apollopre.entity.OrderStateCountBean;
import com.bulletelc.apollopre.entity.ServiceModuleBean;
import com.bulletelc.apollopre.framework.MVPBaseFragment;
import com.bulletelc.apollopre.manager.imageload.ImageLoaderManager;
import com.bulletelc.apollopre.module.main.MainActivity;
import com.bulletelc.apollopre.module.main.center.address.list.AddressActivity;
import com.bulletelc.apollopre.module.main.center.afterSale.ServiceOrderListActivity;
import com.bulletelc.apollopre.module.main.center.bargain.BargainActivity;
import com.bulletelc.apollopre.module.main.center.collection.CollectionActivity;
import com.bulletelc.apollopre.module.main.center.intention.list.IntentionListActivity;
import com.bulletelc.apollopre.module.main.center.invoice.list.InvoiceActivity;
import com.bulletelc.apollopre.module.main.center.orders.OrderListActivity;
import com.bulletelc.apollopre.module.main.center.setting.SettingActivity;
import com.bulletelc.apollopre.module.richscan.RichScanActivity;
import com.bulletelc.apollopre.utils.MyUtil;
import com.bulletelc.apollopre.utils.SharedPreferencesUtil;
import com.bulletelc.apollopre.widget.BadgeView;
import com.bulletelc.apollopre.widget.CustomGridView;
import com.mikelau.croperino.Croperino;
import com.mikelau.croperino.CroperinoConfig;
import com.mikelau.croperino.CroperinoFileUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * author: lhl
 * time  : 2017/10/15
 * desc  : 个人中心界面
 */

public class CenterFragment extends MVPBaseFragment<CenterContract.View, CenterPresenter> implements CenterContract.View, View.OnClickListener,
        OnRefreshListener, AdapterView.OnItemClickListener {

    // views
    private BadgeView vbUnPaid;
    private BadgeView vbUnSend;
    private BadgeView vbUnSign;
    private BadgeView vbUnComment;
    private ProgressBar pbLoad;
    private LinearLayout llUnPaid;
    private LinearLayout llUnSend;
    private LinearLayout llUnSign;
    private LinearLayout llUnComment;
    private CircleImageView civAvatar;
    private TextView tvName;
    private CustomGridView gvServices;
    private ImageButton iBtnSetting, iBtnScan;
    private SmartRefreshLayout refreshLayout;

    // data
    private List<ServiceModuleBean> serviceModuleBeans;
    private ServiceModuleAdapter adapter;
    private static Uri ImageUri; // 头像Uri
    private boolean first = true; // 加载标识符

//    @Override
//    public void onHiddenChanged(boolean hidden) {
//        super.onHiddenChanged(hidden);
//        if (hidden) {
//            return;
//        } else {
//            if (first) {
//                MyUtil.setProgressBar(pbLoad, true);
//                initProfile();
//            }
//        }
//    }

    @Override
    public void onStart() {
        super.onStart();
        MyUtil.setProgressBar(pbLoad, true);
        initProfile();
    }

    @Override
    public int getLayoutRes() {
        return R.layout.center_fragment;
    }

    @Override
    public void assignViews() {

        vbUnPaid = findView(R.id.vbUnPaid);
        vbUnSend = findView(R.id.vbUnSend);
        vbUnSign = findView(R.id.vbUnSign);
        vbUnComment = findView(R.id.vbUnComment);
        refreshLayout = findView(R.id.smartRefreshLayout);
        civAvatar = findView(R.id.civ_avatar);
        tvName = findView(R.id.tvName);
        iBtnSetting = findView(R.id.iBtnSetting);
        iBtnScan = findView(R.id.iBtnScan);
        llUnPaid = findView(R.id.llUnPaid);
        llUnSend = findView(R.id.llUnSend);
        llUnSign = findView(R.id.llUnSign);
        llUnComment = findView(R.id.llUnComment);
        gvServices = findView(R.id.gvServices);
        pbLoad = findView(R.id.pbLoad);

    }

    @Override
    public void setListener() {

        civAvatar.setOnClickListener(this);
        iBtnSetting.setOnClickListener(this);
        iBtnScan.setOnClickListener(this);
        llUnPaid.setOnClickListener(this);
        llUnSend.setOnClickListener(this);
        llUnSign.setOnClickListener(this);
        llUnComment.setOnClickListener(this);
        refreshLayout.setOnRefreshListener(this);
        gvServices.setOnItemClickListener(this);

    }


    @Override
    public void initData(Bundle savedInstanceState) {

        serviceModuleBeans = new ArrayList<>();
        ServiceModuleBean serviceModuleBean1 = new ServiceModuleBean(OrderListActivity.class, R.mipmap.ic_order_all, R.string.order_my);
        ServiceModuleBean serviceModuleBean2 = new ServiceModuleBean(ServiceOrderListActivity.class, R.mipmap.ic_service_order, R.string.center_service);
        ServiceModuleBean serviceModuleBean3 = new ServiceModuleBean(CollectionActivity.class, R.mipmap.ic_collection, R.string.center_collect);
        ServiceModuleBean serviceModuleBean4 = new ServiceModuleBean(AddressActivity.class, R.mipmap.ic_address, R.string.center_address);
        ServiceModuleBean serviceModuleBean5 = new ServiceModuleBean(InvoiceActivity.class, R.mipmap.ic_invoice, R.string.center_invoice);
        ServiceModuleBean serviceModuleBean6 = new ServiceModuleBean(IntentionListActivity.class, R.mipmap.ic_intention, R.string.center_intent_list);
        ServiceModuleBean serviceModuleBean7 = new ServiceModuleBean(BargainActivity.class, R.mipmap.ic_intention, R.string.center_intent_test);
        serviceModuleBeans.add(serviceModuleBean1);
        serviceModuleBeans.add(serviceModuleBean2);
        serviceModuleBeans.add(serviceModuleBean3);
        serviceModuleBeans.add(serviceModuleBean4);
        serviceModuleBeans.add(serviceModuleBean5);
        serviceModuleBeans.add(serviceModuleBean6);
        serviceModuleBeans.add(serviceModuleBean7);
        adapter = new ServiceModuleAdapter(getContext(), serviceModuleBeans);
        gvServices.setAdapter(adapter);

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.civ_avatar:
                exchange(); // 更换头像
                break;
            case R.id.iBtnSetting:
                startActivity(new Intent(getContext(), SettingActivity.class));
                break;

            case R.id.iBtnScan:
                startActivity(new Intent(getContext(), RichScanActivity.class));
                break;

            case R.id.llUnPaid:
                GoToOrderListActivity(1);
                break;

            case R.id.llUnSend:
                GoToOrderListActivity(2);
                break;

            case R.id.llUnSign:
                GoToOrderListActivity(3);
                break;

            case R.id.llUnComment:
                GoToOrderListActivity(4);
                break;
        }
    }

    /**
     *跳转全部订单
     * @param position 订单状态位置
     */
    private void GoToOrderListActivity(int position) {
        Intent intent = new Intent(baseActivity,OrderListActivity.class);
        intent.putExtra(IntentCode.EXTRA_KEY_ORDER_STATE_POSITION, position);
        startActivity(intent);
    }

    @Override
    protected CenterPresenter createPresenter() {
        return new CenterPresenter();
    }

    @Override
    public void onSuccessGetSetting(String name) {
        if ("".equals(name)) {
            tvName.setText("未设置");
        } else {
            tvName.setText(name);
        }
    }

    @Override
    public void onFailGetSetting(String fail) {
        Toast.makeText(baseActivity, fail, Toast.LENGTH_SHORT).show();
        MyUtil.setProgressBar(pbLoad, false);
    }

    @Override
    public void onErrorGetSetting(String error) {
        Toast.makeText(baseActivity, R.string.network_msg, Toast.LENGTH_SHORT).show();
        MyUtil.setProgressBar(pbLoad, false);
    }

    @Override
    public void onSuccessGetAvatar(String url) {
        if ("".equals(url) && url ==null) {
            civAvatar.setImageResource(R.drawable.ic_default_avatar);
        } else {
            ImageLoaderManager.getInstance().loadImage(ImageLoaderManager.getDefaultOptions(civAvatar, url));
        }
        SharedPreferencesUtil.putBoolean(MyApplication.getInstance(), SPKey.SP_CHECK_ISLOAD_AVATAR, false);
        MyUtil.setProgressBar(pbLoad, false);
    }

    @Override
    public void onFailGetAvatar(String msg) {
        Toast.makeText(baseActivity, msg, Toast.LENGTH_SHORT).show();
        MyUtil.setProgressBar(pbLoad, false);
    }

    @Override
    public void onErrorGetAvatar(String msg) {
        MyUtil.setProgressBar(pbLoad, false);
    }

    @Override
    public void onSuccessGetOrderStateCount(OrderStateCountBean orderStateCountBean) {
        setOrderStateCount(orderStateCountBean);
        first = false;
        MyUtil.setProgressBar(pbLoad, false);
    }

    @Override
    public void onFailGetOrderStateCount(String fail) {
        Toast.makeText(baseActivity, fail, Toast.LENGTH_SHORT).show();
        MyUtil.setProgressBar(pbLoad, false);
    }

    @Override
    public void onErrorGetOrderStateCount(String error) {
        MyUtil.setProgressBar(pbLoad, false);
    }

    @Override
    public void onSuccessPostAvatar(String msg) {
        civAvatar.setImageURI(ImageUri);
        Toast.makeText(baseActivity, "更换成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorPostAvatar(String msg) {
        Toast.makeText(baseActivity, R.string.network_msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onFailPostAvatar(String msg) {
        Toast.makeText(baseActivity, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 更换头像重现此fragment的时候
     * 实现MainActivity接口
     */
    @Override
    public void onResume() {
        super.onResume();
        ((MainActivity)getActivity()).setOnActivityResultListener(new MainActivity.onActivityResultListener() {
            @Override
            public void onResultListener(int requestCode, int resultCode, Intent data) {
                if(data == null) {
                    return;
                }
                switch (requestCode) {
                    case CroperinoConfig.REQUEST_TAKE_PHOTO:
                        if (resultCode == Activity.RESULT_OK) {
                            Croperino.runCropImage(CroperinoFileUtil.getmFileTemp(), getActivity(), true, 1, 1, 0, 0);
                        }
                        break;
                    case CroperinoConfig.REQUEST_PICK_FILE:
                        if (resultCode == Activity.RESULT_OK) {
                            CroperinoFileUtil.newGalleryFile(data, getActivity());
                            Croperino.runCropImage(CroperinoFileUtil.getmFileTemp(), getActivity(), true, 1, 1, 0, 0);
                        }
                        break;
                    case CroperinoConfig.REQUEST_CROP_PHOTO:
                        if (resultCode == Activity.RESULT_OK) {
                            Uri i = Uri.fromFile(CroperinoFileUtil.getmFileTemp());
                            presenter.postAvatar(getContext(), i.getPath());
                            ImageUri = i;
                            //civAvatar.setImageURI(i);
                        }
                        break;
                    default:
                        break;
                }
            }
        });
    }

    /**
     * SmartRefreshLayout 监听接口
     * @param refreshlayout
     */
    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshLayout.finishRefresh(400);
        presenter.getOrderStateCount();
        first = true;
        SharedPreferencesUtil.putBoolean(baseActivity, SPKey.SP_CHECK_ISLOAD_AVATAR, true);
        initProfile();
    }

    @Override
    public void onStop() {
        super.onStop();
        SharedPreferencesUtil.putBoolean(MyApplication.getInstance(), SPKey.SP_CHECK_ISLOAD_AVATAR, true);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == CroperinoFileUtil.REQUEST_CAMERA) {
            for (int i = 0; i < permissions.length; i++) {
                String permission = permissions[i];
                int grantResult = grantResults[i];

                if (permission.equals(Manifest.permission.CAMERA)) {
                    if (grantResult == PackageManager.PERMISSION_GRANTED) {
                        prepareCamera();
                    }
                }
            }
        } else if (requestCode == CroperinoFileUtil.REQUEST_EXTERNAL_STORAGE) {
            boolean wasReadGranted = false;
            boolean wasWriteGranted = false;

            for (int i = 0; i < permissions.length; i++) {
                String permission = permissions[i];
                int grantResult = grantResults[i];

                if (permission.equals(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    if (grantResult == PackageManager.PERMISSION_GRANTED) {
                        wasReadGranted = true;
                    }
                }
                if (permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    if (grantResult == PackageManager.PERMISSION_GRANTED) {
                        wasWriteGranted = true;
                    }
                }
            }

            if (wasReadGranted && wasWriteGranted) {
                prepareChooser();
            }
        }
    }


    /**
     * 设置订单数量
     * @param orderStateCountBean
     */
    private void setOrderStateCount(OrderStateCountBean orderStateCountBean) {
        vbUnPaid.setBadgeNum(Integer.parseInt(orderStateCountBean.getNeed_pay()));
        vbUnPaid.redraw();
        vbUnSend.setBadgeNum(Integer.parseInt(orderStateCountBean.getWait_send()));
        vbUnSend.redraw();
        vbUnSign.setBadgeNum(Integer.parseInt(orderStateCountBean.getWait_sign()));
        vbUnSign.redraw();
        vbUnComment.setBadgeNum(Integer.parseInt(orderStateCountBean.getWait_comment()));
        vbUnComment.redraw();
    }

    /**
     * 更换头像
     */
    public void exchange() {
        new CroperinoConfig("IMG_" + System.currentTimeMillis() + ".jpg", "/MikeLau/Pictures", "/sdcard/MikeLau/Pictures");
        CroperinoFileUtil.setupDirectory(getContext());
        if (CroperinoFileUtil.verifyStoragePermissions(getActivity())) {
            prepareChooser();
        }
    }

    private void prepareChooser() {
        Croperino.ChooseImg(getActivity());
//        Croperino.prepareChooser(getActivity(), "请选择打开图片方式", ContextCompat.getColor(getActivity(), R.color.colorPrimary));
    }

    private void prepareCamera() {
        Croperino.prepareCamera(getActivity());
    }

    /**
     * 初始化用户数
     */
    private void initProfile() {
        String token = MyApplication.getToken();
        if (token != null && token.length() > 0) {
            presenter.getSetting();
            presenter.getOrderStateCount();
            presenter.getAvatar();
//            if (SharedPreferencesUtil.getBoolean(MyApplication.getInstance(), SPKey.SP_CHECK_ISLOAD_AVATAR)) {
//                presenter.getAvatar();
//            } else {
//                civAvatar.setImageURI(ImageUri);
//            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Intent intent = new Intent(baseActivity, serviceModuleBeans.get(i).getActivity());
        baseActivity.startActivity(intent);
    }

}
